/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.uca.sisbec.actions.manto;

import com.uca.sisbec.commons.HibernateAction;
import com.uca.sisbec.commons.Utils;
import com.uca.sisbec.forms.manto.BecarioForm;
import com.uca.sisbec.helpers.manto.BecarioHelper;
import com.uca.sisbec.mapping.Carrera;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author Susy
 */
public class BecarioAction extends HibernateAction {

    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String emails = "", phones = "";
        BecarioForm bf = (BecarioForm) form;
        BecarioHelper helper = new BecarioHelper(getSession(request));
        setOptionsLists(request);
        if (bf.getCodUniversidad() != 0)
            request.setAttribute("CarrerasList", helper.getAllCarreras(bf.getCodUniversidad()));
        emails = bf.getEmailsString();
        bf.setEmails(new String[0]);
        bf.setEmailsString(emails);
        phones = bf.getPhonesString();
        bf.setPhones(new String[0]);
        bf.setPhonesString(phones);
        if(bf.getAccion()==null || bf.getAccion().equals("new")){
            request.setAttribute("save", "new");
        }else{
            request.setAttribute("save","update");
        }
        return mapping.findForward("success");
    }

    public ActionForward initBusqueda(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        return mapping.findForward("search");
    }

    public ActionForward AgregarBecario(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("entre a agregar becario");
        BecarioForm bf = (BecarioForm) form;
        ActionMessages msg = new ActionMessages();
        ActionErrors errors = new ActionErrors();
        BecarioHelper helper = new BecarioHelper(getSession(request));
        FileOutputStream outputStream = null;
        FormFile formFile = null;
        formFile = bf.getFile();
        if (helper.validateBecario(bf)) {
            if (!Utils.isNullOrEmpty(formFile.getFileName())){
                String[] ext = formFile.getFileName().split("\\.");
                String fileName2 = bf.getCarnet() + "." + ext[1];
                String path2 = getServlet().getServletContext().getRealPath("") + "\\images\\becarios\\" + bf.getCarnet() + "." + ext[1];
                outputStream = new FileOutputStream(new File(path2));
                outputStream.write(formFile.getFileData());
                System.out.println("El path es: " + path2);
                if (outputStream != null) {
                    System.out.println("Ya subí la foto");
                    bf.setFoto(fileName2);
                    outputStream.close();
                } else {
                    outputStream.close();
                }
            }
            helper.insertarBecarioDB(bf);
            msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("becario.nuevo"));
            request.setAttribute("msg", msg);
            request.setAttribute("save", "update");
        } else {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("becario.existe", bf.getCarnet()));
            request.setAttribute("errors", errors);
            request.setAttribute("save", "new");
        }
        /**/
        
        if(bf.getEmails() != null){
            bf.setEmails(bf.getEmails());
        } else {
            bf.setEmails(new String[0]);
        }
        if(bf.getPhones() != null){
            bf.setPhones(bf.getPhones());
        } else {
            bf.setPhones(new String[0]);
        }
        setOptionsLists(request);
        request.setAttribute("CarrerasList", helper.getAllCarreras(bf.getCodUniversidad()));
        return mapping.findForward("success");

    }

    public ActionForward BuscarBecario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        BecarioForm bf = (BecarioForm) form;
        BecarioHelper helper = new BecarioHelper(getSession(request));
        System.out.println("Entre a BuscarBecario");
        setOptionsLists(request);
        request.setAttribute("becarioData", helper.buscarBecarioDB(bf));
        return mapping.findForward("search");
    }

    public ActionForward SeleccionarBecario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        BecarioForm bf = (BecarioForm) form;
        BecarioHelper helper = new BecarioHelper(getSession(request));
        String carnet = bf.getCarnet();
        helper.buscarBecarioDB(carnet, bf);
        
        
        
        request.setAttribute("save", "update");
        setOptionsLists(request);
        if (bf.getCodUniversidad() != 0)
            request.setAttribute("CarrerasList", helper.getAllCarreras(bf.getCodUniversidad()));
        return mapping.findForward("success");
    }

    public ActionForward ModificarBecario(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        BecarioForm bf = (BecarioForm) form;
        FormFile formFile = null;
        formFile = bf.getFile();
        FileOutputStream outputStream = null;
        System.out.println(formFile.getFileSize());
        if (formFile.getFileSize()!=0){
            String[] ext = formFile.getFileName().split("\\.");
            String path2 = getServlet().getServletContext().getRealPath("") + "\\images\\becarios\\" + bf.getCarnet() + "." + ext[1];
            String fileName2 = bf.getCarnet() + "." + ext[1];
            outputStream = new FileOutputStream(new File(path2));
            outputStream.write(formFile.getFileData());
            if (outputStream != null) {
                bf.setFoto(fileName2);
                outputStream.close();
            } else {
                outputStream.close();
            }
        }else{
            bf.setFoto("");
        }
        //String path = getServlet().getServletContext().getRealPath("") + "\\images\\becarios\\" + formFile.getFileName();

        BecarioHelper helper = new BecarioHelper(getSession(request));

        helper.modificarBecarioDB(bf);
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("becario.modificado"));
        request.setAttribute("msg", msg);
        request.setAttribute("save", "update");
        setOptionsLists(request);
        if (bf.getCodUniversidad() != 0)
            request.setAttribute("CarrerasList", helper.getAllCarreras(bf.getCodUniversidad()));
        /**/
        bf.setEmailsString(bf.getEmailsString());
        bf.setPhonesString(bf.getPhonesString());
        return mapping.findForward("success");
    }

    public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String emails = "", phones = "";
        BecarioForm bf = (BecarioForm) form;
        BecarioHelper helper = new BecarioHelper(getSession(request));
        setOptionsLists(request);
        System.out.println("El atributo es: "+request.getParameter("accion"));
        if (bf.getCodUniversidad() != 0)
            request.setAttribute("CarrerasList", helper.getAllCarreras(bf.getCodUniversidad()));
        if(request.getParameter("accion").equals("new")){
            /* para que no queden seleccionados */
            emails = bf.getEmailsString();
            bf.setEmails(new String[0]);
            bf.setEmailsString(emails);
            phones = bf.getPhonesString();
            bf.setPhones(new String[0]);
            bf.setPhonesString(phones);
        }
        request.setAttribute("save", request.getParameter("accion"));
        return mapping.findForward("success");
    }

    public void setOptionsLists(HttpServletRequest request) {
        BecarioHelper helper = new BecarioHelper(getSession(request));
        request.setAttribute("UniversidadesList", helper.getUniversidadesActivas());
        request.setAttribute("CarrerasList", new ArrayList<Carrera>());
        request.setAttribute("RecomendadorList", helper.getAllRecomendadores());
    }
}
